package com.zmxstudy.gzu.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zmxstudy.gzu.domain.TbPara;
import com.zmxstudy.gzu.domain.TbTemplate;
import com.zmxstudy.gzu.mapper.TbParaMapper;
import com.zmxstudy.gzu.mapper.TbTemplateMapper;
import com.zmxstudy.gzu.utils.ProductCodeMsg;
import com.zmxstudy.gzu.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "参数管理")
@RestController
@RequestMapping("/product-service/Para")
@SuppressWarnings("rawtypes")
public class ParaController {
    @Resource
    TbParaMapper tbParaMapper;
    @Resource
    TbTemplateMapper tbTemplateMapper;


    @Operation(summary = "添加参数，各个字段不能为空")
    @PostMapping
    public Result addPara(@RequestBody TbPara tbPara){
        if (tbPara.getTemplateId() == null || tbPara.getName() == null || tbPara.getOptions() == null){
            return Result.error(ProductCodeMsg.ADD_Para_error);
        }
        TbTemplate tbTemplate = tbTemplateMapper.selectById(tbPara.getTemplateId());
        if (tbTemplate == null){
            return Result.error(ProductCodeMsg.ADD_Para_error);
        }
        tbParaMapper.insert(tbPara);
        return Result.success();
    }

    @Operation(summary = "修改参数，各个字段不能为空")
    @PutMapping
    public Result updatePara(@RequestBody TbPara tbPara){
        if (tbPara.getTemplateId() == null || tbPara.getName() == null || tbPara.getOptions() == null){
            return Result.error(ProductCodeMsg.ADD_Para_error);
        }
        tbParaMapper.updateById(tbPara);
        return Result.success();
    }


    @Operation(summary = "删除参数")
    @DeleteMapping("/{id}")
    public Result deletePara(@PathVariable Long id){
        TbPara tbPara = tbParaMapper.selectById(id);

        if (tbPara == null){
            return Result.error(ProductCodeMsg.DELETE_Para_error);
        }


        tbParaMapper.deleteById(id);
        return Result.success();
    }


    @Operation(summary = "查询所有参数")
    @GetMapping()
    public Result<List<TbPara>> findTbPara(){
        List<TbPara> list = tbParaMapper.selectList(null);
        System.out.println(list);
        return Result.success("查询成功",list);
    }


    @Operation(summary = "查询参数，根据tbTemplate外键id,进行查询")
    @GetMapping("/{id}")
    public Result findPara(@PathVariable Long id){

        LambdaQueryWrapper<TbPara> laq=new LambdaQueryWrapper<>();
        laq.eq(TbPara::getTemplateId,id);
        List<TbPara> list = tbParaMapper.selectList(laq);


        return Result.success("查询成功",list);
    }

}
